package total

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"miners-monitor/models/common"
)

const dbName = "total"

type TotalDbModel struct {
	common.BaseModel
	CommonFunc common.CommonFunc
}


func (this *TotalDbModel) Find(filter interface{}, opts *options.FindOptions) (*mongo.Cursor, error) {
	return this.MDB.Collection(dbName).Find(context.TODO(), filter, opts)
}


func (this *TotalDbModel) FindOne(filter interface{}, opts *options.FindOneOptions) *mongo.SingleResult {
	return this.MDB.Collection(dbName).FindOne(context.TODO(), filter, opts)
}

func (this *TotalDbModel) Upsert(data TotalMiner) {
	updateBsonD, err := this.CommonFunc.StructToBsonD(data)
	if err != nil {
		panic(err)
	}
	filterBsonD, err := this.CommonFunc.StructToBsonD(TotalMiner{
		MinerAddress: data.MinerAddress,
		Height:       data.Height,
	})
	if err != nil {
		panic(err)
	}
	opts := options.Update().SetUpsert(true)
	updateSet := bson.D{{"$set", updateBsonD}}
	_, err = this.MDB.Collection(dbName).UpdateOne(context.Background(), filterBsonD, updateSet, opts)
	if err != nil {
		panic(err)
	}
}

func (this *TotalDbModel) CountDocuments(filter bson.D, opts *options.CountOptions) int64 {
	result, err := this.MDB.Collection(dbName).CountDocuments(context.TODO(), filter, opts)
	if err == mongo.ErrNoDocuments {
		return 0
	} else if err != nil {
		panic(err)
	}
	return result
}